package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    @Transactional
    public User login(UserLoginDTO userLoginDTO) {
        //1. 获取微信的openid
        String openId = getOpenId(userLoginDTO);

        //2. 判断opeinid是否为空 如果为空则抛出异常
        if(null == openId){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //3. 查询当前的用户是否已注册 如果未注册则先注册
        User user = userMapper.getByOpenId(openId);
        if(null == user){
            //表示是一个新用户
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        //4. 构建返回结果并返回
        return user;
    }

    /**
     * 获取微信的openId
     * @param userLoginDTO
     * @return
     */
    private String getOpenId(UserLoginDTO userLoginDTO) {
        Map<String,String> params = new HashMap<>();
        params.put("appid","wx3e491aca80deb7ee");
        params.put("secret","0cf7858d3ea7e5048f8ea989c69af7a1");
        params.put("js_code",userLoginDTO.getCode());
        params.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(LOGIN_URL, params);

        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = (String)jsonObject.get("openid");

        return openid;
    }
}
